package com.sat.learning.Views;

import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sat.learning.R;

import java.text.SimpleDateFormat;

/**
 * Project:Projects
 * Package:com.sat.learning.Views
 * Created by 透野君爱打奶炮 on 2018-03-19 at 07:38
 */
public class RefreshView extends ListView implements AbsListView.OnScrollListener {

    private float downY, moveY;
    public static final int PULL_TO_REFRESH = 0;
    public static final int RELEASE_TO_REFRESH = 1;
    public static final int REFRESHING = 2;
    private int currentState = PULL_TO_REFRESH;
    private int mHeaderViewHeight;
    private View mHeaderView;
    private RotateAnimation rotateUpAnimation,rotateDownAnimation;
    private ImageView iv_header_icon;
    private TextView tv_header_title;
    private TextView tv_header_date;
    private ProgressBar pb;
    private onRefreshListener listener;
    private View mFooterView;
    private int mFooterViewHeight;
    private boolean isLoad;

    public RefreshView(Context context) {
        this(context, null);
    }

    public RefreshView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RefreshView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        initHeaderView();
        initAnim();
        initFooterView();
        setOnScrollListener(this);
    }

    private void initFooterView() {
        mFooterView = View.inflate(getContext(), R.layout.layout_footer_listview, null);
        mFooterView.measure(0,0);
        mFooterViewHeight = mFooterView.getMeasuredHeight();
        mFooterView.setPadding(0,-mFooterViewHeight,0,0);
        addFooterView(mFooterView);
    }

    private void initAnim() {
        rotateUpAnimation = new RotateAnimation(0f, -180f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotateUpAnimation.setDuration(300);
        rotateUpAnimation.setFillAfter(true);

        rotateDownAnimation = new RotateAnimation(-180f, -360f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotateDownAnimation.setDuration(300);
        rotateDownAnimation.setFillAfter(true);
    }

    private void initHeaderView() {
        mHeaderView = View.inflate(getContext(), R.layout.layout_header_listview, null);
        iv_header_icon = (ImageView) mHeaderView.findViewById(R.id.iv_head_icon);
        pb = (ProgressBar) mHeaderView.findViewById(R.id.pb);
        tv_header_title = (TextView) mHeaderView.findViewById(R.id.tv_header_title);
        tv_header_date = (TextView) mHeaderView.findViewById(R.id.tv_header_date);
        mHeaderView.measure(0, 0);
        //Log.d("TAG","height"+mHeaderView.getHeight()+"===mHeight"+mHeaderView.getMeasuredHeight());
        mHeaderViewHeight = mHeaderView.getMeasuredHeight();
        mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
        addHeaderView(mHeaderView);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downY = ev.getY();

                break;
            case MotionEvent.ACTION_MOVE:
                if(currentState == REFRESHING){
                    return super.onTouchEvent(ev);
                }
                moveY = ev.getY();
                float offset = moveY - downY;
                int paddingTop = (int) (offset - mHeaderViewHeight);
                Log.d("TAG", "偏移量="+paddingTop);
                if (offset > 0 && getFirstVisiblePosition() == 0) {
                    mHeaderView.setPadding(0, paddingTop, 0, 0);
                    if (paddingTop >= 0 && currentState != RELEASE_TO_REFRESH) {//完全显示 释放刷新
                        currentState = RELEASE_TO_REFRESH;
//                        Log.d("TAG", "释放刷新" + paddingTop+"---current="+currentState);
                        updateHeader();
                    } else if (paddingTop < 0 && currentState != PULL_TO_REFRESH) {//不完全显示 下拉刷新
                        currentState = PULL_TO_REFRESH;
//                        Log.d("TAG", "下拉刷新" + paddingTop+"---current="+currentState);
                        updateHeader();
                    }
                    return true;
                }

                break;
            case MotionEvent.ACTION_UP:
                if (currentState == PULL_TO_REFRESH){
                    mHeaderView.setPadding(0,-mHeaderViewHeight,0,0);
                }else if (currentState == RELEASE_TO_REFRESH){
                    mHeaderView.setPadding(0,0,0,0);
                    currentState = REFRESHING;
                    updateHeader();
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    /**
     * 根据状态切换头布局内容
     */
    private void updateHeader() {
        switch (currentState){
            case PULL_TO_REFRESH:
                Log.d("TAG","现在是下拉刷新状态");
                iv_header_icon.startAnimation(rotateDownAnimation);
                tv_header_title.setText("下拉刷新");
                break;
            case RELEASE_TO_REFRESH:
                Log.d("TAG","现在是释放刷新状态");
                iv_header_icon.startAnimation(rotateUpAnimation);
                tv_header_title.setText("释放刷新");
                break;
            case REFRESHING:
                iv_header_icon.clearAnimation();
                iv_header_icon.setVisibility(INVISIBLE);
                pb.setVisibility(VISIBLE);
                tv_header_title.setText("正在刷新中...");
                if (listener !=null){
                    listener.onRefresh();
                }
                break;
        }
    }

    public void setRefreshComplete() {
        if (isLoad){
            mFooterView.setPadding(0,-mFooterViewHeight,0,0);
            isLoad=false;
        }else {
            //刷新完成，恢复初始状态
            currentState = PULL_TO_REFRESH;
            mHeaderView.setPadding(0,-mHeaderViewHeight,0,0);
            pb.setVisibility(INVISIBLE);
            iv_header_icon.setVisibility(VISIBLE);

            long l = System.currentTimeMillis();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = simpleDateFormat.format(l);
            tv_header_date.setText("最后刷新时间 "+date);
        }

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_IDLE && getLastVisiblePosition()==(getCount()-1)){
            if (isLoad){
                return;
            }
            Log.d("TAG","下拉");
            mFooterView.setPadding(0,0,0,0);
            isLoad = true;
            setSelection(getCount());
            if (listener!=null){
                listener.onMoreRefresh();
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    public interface onRefreshListener{
        void onRefresh();
        void onMoreRefresh();
    }

    public void setOnRefreshListener(onRefreshListener listener) {
        this.listener = listener;
    }
}
